import React, { useEffect } from 'react'
import { Avatar, Badge, Typography, Dropdown } from 'antd'
import bmsHeaderStyle from './index.less'
import Pubsub from 'pubsub-js'
import { exitLogin } from '../../../public/isLogin'
import { PASSWORD_RESET, REQUEST_INFO } from '../constant'
import { useDispatch, useSelector } from 'react-redux'
import { setRequestInfo } from '../../action/action'
import { getUInfo } from '../../../session/session'

const { Title } = Typography

function BMSHeader () {
  const items = [
    {
      key: '1',
      label: (
        <span onClick={getRequestInfo}>消息</span>
      ),
    },
    {
      key: '2',
      label: (
        <span onClick={passwordReset}>修改密码</span>
      ),
    },
    {
      key: '3',
      label: (
        <span onClick={exit}>退出登录</span>
      ),
    },
  ]
  const requestInfoNum = useSelector(state => {
    return state.toJS().getRequestInfo.length
  })
  const dispatch = useDispatch()

  function exit () {
    exitLogin()
  }

  function passwordReset () {
    Pubsub.publish(PASSWORD_RESET)
  }

  function getRequestInfo () {
    Pubsub.publish(REQUEST_INFO)
  }

  useEffect(() => {
    const uinfo = JSON.parse(getUInfo())
    dispatch(setRequestInfo(uinfo.readerId))
  }, [])

  return (
    <React.Fragment>
        <span className={bmsHeaderStyle.text}>
          <Title level={3} style={{ color: '#c6d4d5' }}>图书管理系统</Title>
        </span>
      <span className={bmsHeaderStyle.avatar}>
          <Dropdown
            menu={{ items }}
          >
            <Badge count={requestInfoNum}>
              <Avatar shape="square">U</Avatar>
            </Badge>
          </Dropdown>
        </span>

    </React.Fragment>
  )
}

export default BMSHeader
